package com.wish.system.kafka;

import com.alibaba.fastjson.JSON;
import com.wish.system.api.domain.SysOperLog;
import com.wish.system.service.ISysOperLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.listener.AcknowledgingMessageListener;
import org.springframework.kafka.support.Acknowledgment;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName Listener
 * @Description TODO
 * @Author gaozijie
 * @Date 2022/5/24 23:16
 */
@Slf4j
public class Listener implements AcknowledgingMessageListener<String,String> {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ISysOperLogService iSysOperLogService;

    @Override
    @KafkaListener(groupId = "test-goods",topics = "test")
    public void onMessage(ConsumerRecord<String, String> consumerRecord, Acknowledgment acknowledgment) {
        String key = consumerRecord.key();

        String value = consumerRecord.value();
        SysOperLog sysOperLog = JSON.parseObject(value, SysOperLog.class);
        log.info("token"+sysOperLog.getToken());
        if(!redisTemplate.opsForValue().setIfAbsent(key,"",10, TimeUnit.MINUTES)){
            return;
        }
        iSysOperLogService.insertOperlog(sysOperLog);
        log.info("开始消费---");
        acknowledgment.acknowledge();
    }
}
